package com.wjy.game.message;

import com.wjy.game.utils.ProtostuffUtil;
import lombok.Data;
import java.io.Serializable;

/**
 * @author wjy
 * @date 2025/5/21 10:17
 * @description 服务器返回
 */
@Data
public class Response<T extends ResMessageData> implements Serializable {

    public final static int SUCCESS = 200;

    public final static int FAIL = 500;

    private int code;

    private String msg;

    private String traceId;

    /**
     * 类名
     */
    private String clsName;

    /**
     * 传输数据
     */
    private byte[] data;

    private Response(byte[] data) {
        this.data = data;
    }

    public Response(int code, String traceId, String clsName, byte[] data) {
        this.code = code;
        this.traceId = traceId;
        this.clsName = clsName;
        this.data = data;
    }

    public Response(int code, String msg, String traceId) {
        this.code = code;
        this.msg = msg;
        this.traceId = traceId;
    }

    public static <T extends ResMessageData> Response<T> success(String traceId, T data) {
        if (data!= null) {
            return new Response<>(SUCCESS, traceId, data.getClass().getName(), ProtostuffUtil.serialize(data));
        } else {
            return new Response<>(SUCCESS, null, traceId);
        }
    }

    public static <T extends ResMessageData> Response<T> fail(String traceId, String msg) {
        return new Response<>(FAIL, msg, traceId);
    }

    public boolean isSuccess() {
        return code == SUCCESS;
    }

    public T getObj() {
        if (clsName != null && !clsName.equals("") && data != null && data.length != 0) {
            try {
                Class<?> aClass = Class.forName(clsName);
                Object obj = ProtostuffUtil.deserialize(data, aClass);
                return (T) obj;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

}
